<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
  <title>大数转换工具</title>
  <style>
    body {
      background-color: #f5f5f5;
      color: #222;
      font-family: "Segoe UI", "Microsoft YaHei", sans-serif;
      margin: 0;
      padding: 10px;
      display: flex;
      flex-direction: column;
      align-items: center;
      min-height: 100vh;
      box-sizing: border-box;
    }
    h1 {
      font-size: 1.6em;
      margin: 0 0 5px;
    }
    .notice {
      color: #b30000;
      font-weight: bold;
      margin-bottom: 10px;
      text-align: center;
      font-size: 0.9em;
    }
    .input-container {
      display: flex;
      align-items: center;
      gap: 8px;
      margin-bottom: 10px;
    }
    .input-area {
      display: flex;
      position: relative;
    }
    input {
      width: 250px;
      padding: 8px;
      font-size: 0.9em;
      border: 1px solid #ccc;
      border-radius: 6px;
    }
    .clear-btn {
      position: absolute;
      right: 8px;
      top: 50%;
      transform: translateY(-50%);
      background: none;
      border: none;
      color: #999;
      cursor: pointer;
      font-size: 1.2em;
      padding: 0 5px;
    }
    .clear-btn:hover {
      color: #333;
    }
    .action-btn {
      background-color: #007bff;
      color: white;
      border: none;
      padding: 8px 12px;
      font-size: 0.9em;
      cursor: pointer;
      border-radius: 6px;
    }
    .action-btn:hover {
      background-color: #0056b3;
    }
    #resultBox {
      margin-top: 5px;
      padding: 10px 15px;
      border: 1px solid #333;
      background-color: #fff;
      font-size: 1em;
      border-radius: 6px;
      min-width: 200px;
      text-align: center;
      cursor: pointer;
      user-select: all;
    }
    .grid {
      display: grid;
      grid-template-columns: repeat(4, 1fr);
      gap: 8px;
      margin-top: 15px;
      max-width: 600px;
    }
    .grid button {
      background-color: #007bff;
      color: white;
      border: none;
      padding: 16px 0;
      font-size: 1em;
      cursor: pointer;
      border-radius: 6px;
    }
    .grid button:hover {
      background-color: #0056b3;
    }
    .example {
      font-size: 0.9em;
      margin: 10px 0;
      color: #555;
    }
    .calculation-log {
      font-size: 0.8em;
      margin: 5px 0;
      color: #666;
      max-width: 500px;
      text-align: center;
    }
  </style>
</head>
<body>
<h1>大数转换工具</h1>
<p class="notice">※本工具支持"无量大数 (e68)"及以下单位，可组合多个单位输入</p>
<p class="example">例如：254.4万极极极 = 2.544e152、254.4万极极极极 = 2.544e200</p>
<div class="calculation-log" id="calculationLog"></div>

<div class="input-container">
  <div class="input-area">
    <input type="text" id="numberInput" placeholder="例如：254.4万极极极 或 23.23兆极极极极">
    <button class="clear-btn" onclick="clearInput()">×</button>
  </div>
  <button class="action-btn" onclick="convert()">转换</button>
</div>

<div id="resultBox" onclick="copyResult()">转换结果将显示在这里</div>

<div class="grid" id="buttons"></div>

<script>
  // 中文大数单位及其对应的指数（10的幂）
  const mapping = {
    "万": 4, "亿": 8, "兆": 12, "京": 16,
    "垓": 20, "秭": 24, "穰": 28, "沟": 32,
    "涧": 36, "正": 40, "载": 44, "极": 48,
    "恒河沙": 52, "阿僧祇": 56, "那由他": 60,
    "不可思议": 64, "无量大数": 68
  };

  // 按单位长度排序（长单位优先匹配）
  const sortedUnits = Object.keys(mapping).sort((a, b) => b.length - a.length);

  const buttonContainer = document.getElementById("buttons");
  for (const key in mapping) {
    const btn = document.createElement("button");
    btn.textContent = key;
    btn.onclick = () => {
      const input = document.getElementById("numberInput");
      input.value += key; // 添加单位
      convert(); // 点击按钮时立即转换
    };
    buttonContainer.appendChild(btn);
  }

  const numberInput = document.getElementById("numberInput");
  numberInput.addEventListener("keydown", (event) => {
    if (event.key === "Enter") {
      convert();
    }
    toggleClearButton();
  });

  numberInput.addEventListener("input", toggleClearButton);

  // 切换清空按钮显示状态
  function toggleClearButton() {
    const clearBtn = document.querySelector(".clear-btn");
    clearBtn.style.display = numberInput.value.trim() ? "block" : "none";
  }

  // 清空输入
  function clearInput() {
    const input = document.getElementById("numberInput");
    input.value = "";
    document.getElementById("resultBox").textContent = "转换结果将显示在这里";
    document.getElementById("calculationLog").textContent = "";
    toggleClearButton();
    input.focus();
  }

  // 转换为科学计数法（保留三位小数）
  function toScientificNotation(num) {
    if (num === 0) return "0";

    if (Math.abs(num) < 1) {
      let exponent = 0;
      let scaled = num;
      while (Math.abs(scaled) < 1) {
        scaled *= 10;
        exponent--;
      }
      return `${parseFloat(scaled.toFixed(3))}e${exponent}`;
    } else {
      let exponent = 0;
      let scaled = num;
      while (Math.abs(scaled) >= 10) {
        scaled /= 10;
        exponent++;
      }
      return `${parseFloat(scaled.toFixed(3))}e${exponent}`;
    }
  }

  function convert() {
    const input = numberInput.value.trim();
    let result = "";
    let calculationLog = "";

    // 分离数字部分和单位部分
    const numMatch = input.match(/^([\d.]+)?/);
    const numPart = numMatch ? numMatch[1] : "";
    const unitStr = input.replace(/^[\d.]*/, '').trim();

    if (unitStr) {
      // 解析单位字符串计算总指数
      let totalExponent = 0;
      let remainingStr = unitStr;
      let isValid = true;
      let unitBreakdown = [];

      while (remainingStr.length > 0 && isValid) {
        let matched = false;

        for (const unit of sortedUnits) {
          if (remainingStr.startsWith(unit)) {
            const unitValue = mapping[unit];
            totalExponent += unitValue;
            unitBreakdown.push(`${unit} (e${unitValue})`);
            remainingStr = remainingStr.slice(unit.length);
            matched = true;
            break;
          }
        }

        if (!matched) {
          isValid = false;
        }
      }

      if (!isValid) {
        result = `无效单位: "${unitStr}"`;
      } else {
        const numericVal = parseFloat(numPart || "1");

        if (isNaN(numericVal)) {
          result = "数字无效";
        } else if (numericVal > 9999.9999999999) {
          result = "无法转换（数值过大）";
        } else {
          const scientificNum = toScientificNotation(numericVal);
          const numExpMatch = scientificNum.match(/e([+-]?\d+)$/);
          const unitExp = totalExponent;

          if (numExpMatch) {
            const numExp = parseInt(numExpMatch[1]);
            const totalExp = numExp + unitExp;
            const significand = scientificNum.replace(/e.*$/, '');
            result = `${significand}e${totalExp}`;

            calculationLog = `计算: ${numPart} → ${scientificNum}, 单位: ${unitBreakdown.join("+")} = e${unitExp}, 总指数: ${numExp} + ${unitExp} = ${totalExp}`;
          } else {
            result = `${scientificNum}e${unitExp}`;
            calculationLog = `计算: ${numPart} → ${scientificNum}, 单位总和: e${unitExp}`;
          }
        }
      }
    } else if (numPart) {
      const numericVal = parseFloat(numPart);
      if (numericVal > 9999.9999999999) {
        result = "无法转换（数值过大）";
      } else {
        result = toScientificNotation(numericVal);
        calculationLog = `计算: ${numPart} → ${result}`;
      }
    } else {
      result = "请输入内容";
      calculationLog = "";
    }

    document.getElementById("resultBox").textContent = result;
    document.getElementById("calculationLog").textContent = calculationLog;
    toggleClearButton();
  }

  function copyResult() {
    const resultBox = document.getElementById("resultBox");
    const text = resultBox.textContent;
    if (text && text !== "转换结果将显示在这里") {
      navigator.clipboard.writeText(text);
      const originalText = text;
      resultBox.textContent = "已复制！";
      setTimeout(() => {
        resultBox.textContent = originalText;
      }, 1500);
    }
  }

  toggleClearButton();
</script>
</body>
</html>
